<template>
  <div class="app-container table-app-container">
    <div class="fixed-table">
      <div class="fixed-table-actionbar" style="display: flex; justify-content: space-between; margin-top: 10px;">
        <div>
          <span>关系变更</span>
        </div>
        <ActionBar v-if="!view" :instance-id="instanceId" @addRow="addRow" />
      </div>

      <PageableTable
        v-if="isRouterAlive"
        ref="table"
        :loading="false"
        :data="tableData"
        :table-height="500"
        :row-class-name="tableRowClassName"
        :disable-pageable="true"
        :multiple-selected="false"
        class="fixed-table-table"
      >
        <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
        <!-- 普通视图 -->
        <el-table-column v-if="!view" label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button v-show="row.addFlag" type="text" title="编辑" size="mini" icon="el-icon-edit" @click="edit(row)" />
            <el-button v-show="!row.addFlag" type="text" title="编辑" size="mini" icon="el-icon-edit" @click="existEdit(row)" />
            <el-button v-show="row.addFlag" type="text" title="删除" size="mini" icon="el-icon-delete" @click="remove(row)" />
            <el-button v-show="!row.addFlag" :type="row.deleteFlag ? 'danger': 'text' " title="实例已有的关系，在流程中只做删除标记，流程完毕之后真正删除。" size="mini" icon="el-icon-delete" @click="fakeRemove(row)" />
            <el-button v-show="!row.addFlag" title="取消选择" type="text" size="mini" icon="el-icon-back" @click="onCancelRelation(row)" />
          </template>
        </el-table-column>
        <!-- 查看视图 -->
        <el-table-column v-if="view" label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button v-show="!row.addFlag && row.deleteFlag" :type="row.deleteFlag ? 'danger': 'text' " title="实例将在工单结束后被删除" size="mini" icon="el-icon-delete" />
            <el-button v-show="row.addFlag" type="text" title="查看" size="mini" icon="el-icon-view" @click="editView(row)" />
            <el-button v-show="!row.addFlag && !row.deleteFlag" type="text" title="查看" size="mini" icon="el-icon-view" @click="existEditView(row)" />
          </template>
        </el-table-column>
      </PageableTable>
      <FormDialog title="编辑" :show.sync="dialogFormVisible" :append-to-body="true" width="40%" @on-ok="ok" @on-cancel="cancel">
        <EditForm :id="editId" ref="editForm" :row="relationRow" :instance-id="instanceId" @editRow="editRow" />
      </FormDialog>
      <FormDialog class="fixed-dialog-height" title="编辑" :show.sync="existDialogFormVisible" :append-to-body="true" @on-ok="existOk" @on-cancel="existCancel">
        <ExistEditForm :id="editId" ref="editForm" :row="existRelationRow" :instance-id="instanceId" @existEditRow="existEditRow" />
      </FormDialog>
      <FormDialog title="查看" :show.sync="viewDialogFormVisible" :append-to-body="true" width="40%" @on-ok="ok" @on-cancel="editViewCancel">
        <EditFormView :id="editId" ref="editForm" :row="relationRow" :instance-id="instanceId" @editRow="editRow" />
      </FormDialog>
      <FormDialog title="查看" :show.sync="viewExistDialogFormVisible" :append-to-body="true" width="40%" @on-ok="ok" @on-cancel="existEditViewCancel">
        <ExistEditFormView :id="editId" ref="editForm" :row="existRelationRow" :instance-id="instanceId" @editRow="editRow" />
      </FormDialog>
    </div>
  </div>
</template>

<script>
import FormDialog from '@neu/biz-core/components/FormDialog'
// 表格查询组件独立编写，需要传递pageable-table实例的mixin方法filter
// 编辑实例组件独立编写，需要传递id属性，判断新建还是更新操作
import EditForm from './components/editForm'
import ExistEditForm from './components/existEditForm'
import ActionBar from './components/actionBar'
import PageableTable from '@neu/biz-core/components/PageableTable'
import EditFormView from './components/editFormView'
import ExistEditFormView from './components/existEditFormView'

function deepCopyObj(obj) {
  if (typeof obj !== 'object') {
    return obj
  }
  var newobj = {}
  for (var attr in obj) {
    newobj[attr] = deepCopyObj(obj[attr])
  }
  return newobj
}

const addFormItem = {
  desc: '',
  src: '',
  srcDesc: '',
  dest: '',
  destDesc: '',
  rela: '',
  relaDesc: '',
  attrs: [],
  descChange: '',
  attrsChange: [],
  relationId: '',
  index: ''
}

export default {
  name: 'ChangeCiRelationPage',
  components: {
    FormDialog,
    EditForm,
    ActionBar,
    PageableTable,
    ExistEditForm,
    EditFormView,
    ExistEditFormView
  },
  // 加入混入，使表格混入更多的api操作
  // mixins: [databind],
  props: {
    multipleSelected: {
      type: Boolean,
      default: false
    },
    instanceId: {
      required: true,
      type: String
    },
    view: {
      required: false,
      type: Boolean
    },
    relationData: {
      required: false,
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      // r: page,
      // d: remove,
      insideColumns: [
        {
          title: '类型',
          key: 'addFlag',
          render: (h, params) => {
            if (params.row.addFlag) {
              return '新增'
            }
            return '已有'
          }
        },
        {
          title: '描述',
          key: 'desc'
        },
        {
          title: '源实例',
          key: 'srcDesc'
        },
        {
          title: '目标实例',
          key: 'destDesc'
        },
        {
          title: '所属关联',
          key: 'relaDesc'
        }
      ],
      dialogFormVisible: false,
      existDialogFormVisible: false,
      viewDialogFormVisible: false,
      viewExistDialogFormVisible: false,
      textMap: {
        update: '编辑',
        create: '新建'
      },
      dialogStatus: 'create',
      editId: -1,
      addFlag: true,
      relationRow: {
        ...addFormItem
      },
      existRelationRow: {
        ...addFormItem
      },
      tableData: [],
      isRouterAlive: true
    }
  },
  watch: {
    relationData: {
      handler(newVal, oldVal) {
        this.tableData = this.relationData
      },
      immediate: true
    }
  },
  created() {},
  methods: {
    // 表格编辑按钮点击事件处理
    edit(row) {
      // 打开对话框
      this.dialogFormVisible = true
      // 更新当前被编辑实体的ID，自动传递至编辑表单
      // this.editId = row.id
      this.editId = row.index
      this.relationRow = deepCopyObj(row)
    },
    // 已存在关系编辑
    existEdit(row) {
      // 打开对话框
      this.existDialogFormVisible = true
      // 更新当前被编辑实体的ID，自动传递至编辑表单
      this.editId = row.index
      this.existRelationRow = deepCopyObj(row)
    },
    // 编辑资产对话框确认事件处理
    ok() {
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        this.reload()
        // 关闭对话框
        this.dialogFormVisible = false
      })
    },
    cancel() {
      this.editId = -1
      this.$refs.editForm.reset()
      // 关闭对话框
      this.dialogFormVisible = false
    },
    // 编辑确认事件处理
    existOk() {
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        // 调用pageable-table实例的mixin方法refresh()，更新表格
        // this.refresh()
        this.reload()
        // 关闭对话框
        this.existDialogFormVisible = false
      })
    },
    existCancel() {
      this.editId = -1
      this.$refs.editForm.reset()
      // 关闭对话框
      this.existDialogFormVisible = false
    },
    remove(row) {
      this.$confirm('删除实例关系?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(row.index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    // 已有关系只做删除标记
    fakeRemove(row) {
      if (!row.deleteFlag) {
        row.deleteFlag = true
      } else {
        row.deleteFlag = false
      }
      this.tableData[row.index] = row
    },
    // 撤销选择已有关系，删除DCOM保存的数据
    onCancelRelation(row) {
      this.$confirm('撤销选择当前实例关系?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(row.index, 1)
        this.$message({
          type: 'success',
          message: '撤销成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    // 设置行索引
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    editRow(row) {
      this.tableData[row.index] = deepCopyObj(row)
    },
    addRow(row) {
      if (this.tableData == null) {
        this.tableData = []
      }
      if (row.relationId) {
        // 已有关系，需要判断去重
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].relationId === row.relationId) {
            return
          }
        }
        this.tableData.push(row)
      } else {
        // 新增关系，直接添加即可
        this.tableData.push(row)
      }
    },
    existEditRow(row) {
      this.tableData[row.index] = deepCopyObj(row)
    },
    // 表格刷新
    reload() {
      this.isRouterAlive = false
      this.$nextTick(function() {
        this.isRouterAlive = true
      })
    },
    // 新增类型关系查看页面
    editView(row) {
      // 打开对话框
      this.viewDialogFormVisible = true
      // 更新当前被编辑实体的ID，自动传递至编辑表单
      // this.editId = row.id
      this.editId = row.index
      this.relationRow = deepCopyObj(row)
    },
    // 新增类型关系查看页面关闭对话框
    editViewCancel() {
      this.editId = -1
      // this.$refs.editForm.reset()
      // 关闭对话框
      this.viewDialogFormVisible = false
    },
    // 已有类型关系查看页面
    existEditView(row) {
      // 打开对话框
      this.viewExistDialogFormVisible = true
      // 更新当前被编辑实体的ID，自动传递至编辑表单
      this.editId = row.index
      this.existRelationRow = deepCopyObj(row)
    },
    // 已有类型关系查看页面关闭对话框
    existEditViewCancel() {
      this.editId = -1
      // 关闭对话框
      this.viewExistDialogFormVisible = false
    }
  }
}
</script>
